<template>
  <div class="user-info-page">
    <div class="page-container">
      <!-- 页面标题 -->
<!--      <div class="page-header">-->
<!--        <h1 class="page-title">个人信息</h1>-->
<!--      </div>-->

      <!-- 个人信息卡片 -->
      <div class="info-card">
        <div class="card-header">
          <div class="avatar-section">
            <a-avatar :size="80" :src="formData.userAvatar" class="user-avatar">
              <template #icon><UserOutlined /></template>
            </a-avatar>
            <div class="avatar-info">
              <h3>{{ formData.userName || '未设置昵称' }}</h3>
              <p>{{ formData.userAccount }}</p>
            </div>
          </div>
        </div>

        <!-- 表单内容 -->
        <div class="card-content">
          <a-form
            :model="formData"
            :rules="formRules"
            layout="vertical"
            class="user-form"
            ref="formRef"
          >
            <div class="form-row">
              <!-- 账户（不可编辑） -->
              <a-form-item label="账户" class="readonly-item">
                <a-input
                  v-model:value="formData.userAccount"
                  disabled
                  size="large"
                  class="readonly-input"
                >
                  <template #prefix>
                    <UserOutlined class="input-icon" />
                  </template>
                </a-input>
              </a-form-item>

              <!-- 创建时间（不可编辑） -->
              <a-form-item label="创建时间" class="readonly-item">
                <a-input
                  :value="formatDate(formData.createTime)"
                  disabled
                  size="large"
                  class="readonly-input"
                >
                  <template #prefix>
                    <CalendarOutlined class="input-icon" />
                  </template>
                </a-input>
              </a-form-item>
            </div>

            <div class="form-row">
              <!-- 昵称（可编辑） -->
              <a-form-item label="昵称" name="userName">
                <a-input
                  v-model:value="formData.userName"
                  placeholder="请输入昵称"
                  size="large"
                  class="editable-input"
                  :maxlength="20"
                  show-count
                >
                  <template #prefix>
                    <EditOutlined class="input-icon" />
                  </template>
                </a-input>
              </a-form-item>

              <!-- 用户权限（不可编辑） -->
              <a-form-item label="权限" class="readonly-item">
                <a-input
                  v-model:value="formData.userRole"
                  disabled
                  size="large"
                  class="readonly-input"
                >
                  <template #prefix>
                    <key-outlined class="input-icon" />
                  </template>
                </a-input>
              </a-form-item>
            </div>

            <!-- 个人简介（可编辑） -->
            <a-form-item label="个人简介" name="userProfile">
              <a-textarea
                v-model:value="formData.userProfile"
                placeholder="请输入个人简介"
                :rows="3"
                :maxlength="200"
                show-count
                class="editable-textarea"
              />
            </a-form-item>

            <!-- 操作按钮 -->
            <div class="form-actions">
              <a-button
                type="primary"
                size="large"
                :loading="submitLoading"
                @click="handleSubmit"
                class="submit-btn"
              >
                <template #icon><SaveOutlined /></template>
                提交修改
              </a-button>
              <a-button
                size="large"
                @click="handleReset"
                class="reset-btn"
              >
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </div>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  CalendarOutlined,
  EditOutlined,
  KeyOutlined,
  SaveOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/user'
import axios from '@/router/request'
import { userInfoUpdate } from '@/api/userController.ts'

// 用户状态管理
const userStore = useLoginUserStore()

// 表单引用
const formRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  userAccount: '',
  userName: '',
  userAvatar: '',
  userRole: '',
  userProfile: '',
  createTime: ''
})

// 原始数据备份（用于重置）
const originalData = reactive({
  userAccount: '',
  userName: '',
  userAvatar: '',
  userRole: '',
  userProfile: '',
  createTime: ''
})

// 表单验证规则
const formRules = {
  userName: [
    { max: 20, message: '昵称不能超过20个字符', trigger: 'blur' }
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 初始化用户数据
const initUserData = async () => {
  const user = userStore.loginUser

  // 如果用户信息不存在或者没有ID，尝试重新获取
  if (!user || !user.id) {
    try {
      await userStore.fetchLoginUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      message.error('获取用户信息失败，请重新登录')
      return
    }
  }

  // 使用最新的用户信息
  const currentUser = userStore.loginUser
  if (currentUser && currentUser.id) {
    Object.assign(formData, {
      userAccount: currentUser.userAccount || '',
      userName: currentUser.userName || '',
      userAvatar: currentUser.userAvatar || '',
      userRole: currentUser.userRole === "user" ? "普通用户" : "管理员",
      userProfile: currentUser.userProfile || '',
      createTime: currentUser.createTime || ''
    })

    // 备份原始数据
    Object.assign(originalData, formData)
  }
}

// 提交修改
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    submitLoading.value = true

    // 构建提交数据（只提交可编辑的字段）
    const updateData =<API.UserInfoUpdateRequest>{
      id: userStore.loginUser.id,
      userName: formData.userName,
      userProfile: formData.userProfile
    }

    // 调用更新接口（占位代码）
    const response = await userInfoUpdate(updateData)

    if (response.data.code === 0 && response.data.data) {
      message.success('个人信息更新成功！')

      // 更新本地用户状态
      userStore.setLoginUser({
        ...userStore.loginUser,
        ...updateData
      })

      // 更新原始数据
      Object.assign(originalData, formData)
    } else {
      message.error(response.data.message || '更新失败，请重试')
    }

  } catch (error) {
    console.error('更新个人信息失败:', error)
    message.error('更新失败，请检查网络连接')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  Object.assign(formData, originalData)
  formRef.value?.clearValidate()
  message.info('已重置为原始数据')
}

// 组件挂载时初始化数据
onMounted(async () => {
  await initUserData()
})
</script>

<style scoped>
.user-info-page {
  min-height: 695px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2f5 100%);
  padding: 3% 0;
}

.page-container {
  max-width: 1000px;
  max-height: 500px;
  margin: 0 auto;
}

.page-header {
  text-align: right;
  margin-bottom: 32px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.1),
    0 2px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  width: 1000px;
}

.card-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
  color: white;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-avatar {
  border: 4px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.avatar-info h3 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.avatar-info p {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

.card-content {
  padding: 18px;
}

.user-form {
  max-width: 100%;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 8px;
}

.readonly-item :deep(.ant-form-item-label > label) {
  color: #999;
  font-weight: 500;
}

.readonly-input {
  background: #f5f5f5 !important;
  color: #999 !important;
  cursor: not-allowed;
}

.readonly-input :deep(.ant-input) {
  background: #f5f5f5 !important;
  color: #999 !important;
  cursor: not-allowed;
}

.editable-input,
.editable-textarea {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.editable-input:hover,
.editable-input:focus,
.editable-textarea:hover,
.editable-textarea:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-icon {
  color: #667eea;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.submit-btn {
  height: 48px;
  padding: 0 32px;
  border-radius: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.submit-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.submit-btn:hover::before {
  left: 100%;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #7c8cff 0%, #8a5fb8 100%);
}

.reset-btn {
  height: 48px;
  padding: 0 32px;
  border-radius: 24px;
  border: 2px solid #667eea;
  color: #667eea;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  background: transparent;
}

.reset-btn:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* 覆盖 Ant Design 样式 */
:deep(.ant-form-item-label > label) {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-form-item-explain-error) {
  font-size: 12px;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
}

:deep(.ant-input) {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 0 16px;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .card-header,
  .card-content {
    padding: 24px 20px;
  }

  .form-actions {
    flex-direction: column;
    align-items: center;
  }

  .submit-btn,
  .reset-btn {
    width: 100%;
    max-width: 300px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .user-avatar {
    width: 60px !important;
    height: 60px !important;
  }

  .avatar-info h3 {
    font-size: 20px;
  }

  .avatar-info p {
    font-size: 14px;
  }
}
</style>
